package com.caiyi.financial.nirvana.sms.gateway.http;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.entity.SmsReceiveMessage;
import com.caiyi.financial.nirvana.sms.enums.ReturnCodeEnum;
import com.caiyi.financial.nirvana.sms.enums.SmsMsgStatusEnum;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.queue.NotifyQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.ReceiveMsgQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.SendQueueEntity;
import com.caiyi.financial.nirvana.sms.util.MD5Util;
import org.jdom2.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 营销，领创盛世
 * time:2018.6.4
 */
public class LingChuangGateway extends BaseGateway {

    private static final Logger logger = LoggerFactory.getLogger(LingChuangGateway.class);

    @Override
    public void sendMessage(SendQueueEntity entity) {
        int status = SmsMsgStatusEnum.REQUEST_FAIL.index;
        String result = null;
        try {
            Map<String, String> params = buildParam(entity);
            String response = doPost(info.getServerAddr() + "v2sms.aspx", params);
            logger.info("LingChuangGateway sendMessage response {}, params {}", response, JSON.toJSONString(params));
            List<Element> xmlElement = xmlElement(response);
            if (xmlElement != null && "Success".equalsIgnoreCase(xmlElement.get(0).getValue())) {
                status = SmsMsgStatusEnum.REQUEST_SUCCESS.index;
                //tiskid
                result = xmlElement.get(3).getValue();
            } else {
                //errorcode
                result = xmlElement == null ? "网关请求超时" : xmlElement.get(0).getValue();
            }
        } catch (Exception e) {
            logger.error("LingChuangGateway sendMessage error ! ", e);
            result = "";
        } finally {
            handlerResponse(entity, result, status);
        }
    }

    private Map<String, String> buildParam(SendQueueEntity entity) {
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("userid", info.getAccessNumber());
        logger.info("userid {}", info.getAccessNumber());
        paramsMap.put("action", "send");
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        paramsMap.put("timestamp", timeStamp);
        String sign = MD5Util.encode(info.getAccount() + info.getPassword() + timeStamp);
        paramsMap.put("sign", sign.toLowerCase());
        paramsMap.put("mobile", entity.getPhone());
        paramsMap.put("content", entity.getContent());
        paramsMap.put("sendTime", "");
        paramsMap.put("extno", "");
        return paramsMap;
    }

    @Override
    public boolean notifyStatus(NotifyQueueEntity entity) {
        return false;
    }

    @Override
    public boolean receiveMsg(ReceiveMsgQueueEntity entity) {
        return false;
    }

    //主动查询获取报告状态
    public boolean queryStatus() {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append(info.getServerAddr()).append("v2statusApi.aspx");
            builder.append("?userid=").append(info.getAccessNumber());
            builder.append("&action=").append("query");
            builder.append("&statusNum=").append(1000);
            String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            builder.append("&timestamp=").append(timeStamp);
            String sign = MD5Util.encode(info.getAccount() + info.getPassword() + timeStamp);
            builder.append("&sign=").append(sign.toLowerCase());
            String response = doGet(builder.toString());
            logger.info("LingChuangGateway queryStatus url : {}, result : {}", builder.toString(), response);
            List<Element> elementList = xmlElement(response);
            for (Element element : elementList) {
                int status = SmsMsgStatusEnum.SEND_FAIL.index;
                List<Element> childrenElements = element.getChildren();
                String phone = childrenElements.get(0).getValue();
                String taskId = childrenElements.get(1).getValue();
                String errorCode = childrenElements.get(4).getValue();
                if ("DELIVRD".equals(errorCode)) {
                    status = SmsMsgStatusEnum.SEND_SUCCESS.index;
                }
                String messageId = JedisService.hget(JedisKey.SMS_REMOTE_ID_MESSAGE_ID, taskId + phone);
                JedisService.hdel(JedisKey.SMS_REMOTE_ID_MESSAGE_ID, taskId + phone);
                receiveReport(status, messageId, errorCode);
            }
            return true;
        } catch (Exception e) {
            logger.error("LingChuangGateWay queryStatus error ! ", e);
        }
        return false;
    }

    //主动获取上行信息
    public boolean queryReceiveMsg() {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append(info.getServerAddr()).append("v2callApi.aspx");
            builder.append("?userid=").append(info.getAccessNumber());
            builder.append("&action=").append("query");
            String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            builder.append("&timestamp=").append(timeStamp);
            String sign = MD5Util.encode(info.getAccount() + info.getPassword() + timeStamp);
            builder.append("&sign=").append(sign.toLowerCase());
            String response = doGet(builder.toString());
            logger.info("LingChuangGateway queryReceiveMsg url : {}, result : {}", builder.toString(), response);
            List<Element> elementList = xmlElement(response);
            for (Element element : elementList) {
                List<Element> childrenElements = element.getChildren();
                String phone = childrenElements.get(0).getValue();
                String taskId = childrenElements.get(1).getValue();
                String content = childrenElements.get(2).getValue();
                String messageId = JedisService.hget(JedisKey.SMS_REMOTE_ID_MESSAGE_ID, taskId + phone);
                SmsReceiveMessage smsReceiveMessage = new SmsReceiveMessage();
                smsReceiveMessage.setCreateTime(new Date());
                smsReceiveMessage.setPhone(phone);
                smsReceiveMessage.setContent(content);
                smsReceiveMessage.setMessageId(messageId);
                receiveMessage(smsReceiveMessage);
            }
            return true;
        } catch (Exception e) {
            logger.error("LingChuangGateway queryReceiveMsg error ! ", e);
        }
        return false;
    }

    @Override
    public int queryBalance() {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append(info.getServerAddr()).append("v2sms.aspx");
            builder.append("?userid=").append(info.getAccessNumber());
            builder.append("&action=").append("overage");
            String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            builder.append("&timestamp=").append(timeStamp);
            String sign = MD5Util.encode(info.getAccount() + info.getPassword() + timeStamp);
            builder.append("&sign=").append(sign.toLowerCase());
            String response = doGet(builder.toString());
            logger.info("LingChuangGateWay queryBalance url : {}, result : {}", builder.toString(), response);
            List<Element> elements = xmlElement(response);
            String overage = null;
            int ret = 0;
            try {
                if (elements != null && elements.size() > 1 && "Sucess".equals(elements.get(0).getValue())) {
                    Element element = elements.get(3);
                    overage = element.getValue();
                }
                logger.info("{} 余额查询结果:{}", info.getName(), overage);
                ret = Integer.parseInt(overage);
            } catch (Exception e) {
            }
            return ret;
        } catch (Exception e) {
            logger.error("LingChuangGateWay queryBalance error ! ", e);
        }
        return 0;
    }
}
